﻿using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ConferenceTransferEvidence")]
	public class ConferenceTransferEvidenceController : BaseDbController
	{
		[Route("Index/{ConferenceId}")]
		public async Task<ActionResult> Index(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			ViewBag.ConferenceId = conferenceId;
			ViewBag.ConferenceName = conferenceMaster.ConferenceName;
			ViewBag.ControllerName = Resources.ConferenceTransferEvidence;
			ViewBag.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var model = new ConferenceTransferEvidenceModel();
			model.ConferenceId = conferenceId;
			LoginUser.ConferenceFunctionIdList = Utility.GetConferenceFunctionIdList(conferenceId);
			return View(model);
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ConferenceTransferEvidenceModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = from info in DbContext.ConferenceAttendenceInfo.AsNoTracking().Where(x => x.ConferenceId == model.ConferenceId)
				  join tran in DbContext.TransferEvidenceMaster.AsNoTracking().Where(x => x.Status == ConstValues.Status.正常)
				    on info.ID equals tran.AttendenceId
				  join master in DbContext.ConferenceMaster.AsNoTracking()
				  on info.ConferenceId equals master.ID
				  orderby info.Sort ascending, info.UpdateDate descending
				  select new
				  {
					  ID = tran.ID,
					  FullName = info.FullName,
					  TransferEvidenceId = info.TransferEvidenceId,
					  UploadUrl = tran.UploadUrl,
					  Currency = info.Currency,
					  TotalFee = info.TotalFee,
					  Discount = info.Discount,
					  CreateDate = tran.CreateDate,
					  CreateIP = tran.CreateIP,
					  Creator = tran.Creator,
					  Sort = tran.Sort,
					  HasPaid = info.HasPaid,
					  Status = tran.Status,
					  BenefitEndDate = master.BenefitEndDate,
					  BenefitStartDate = master.BenefitStartDate,
					  Remark = tran.Remark
				  };

			if (!string.IsNullOrWhiteSpace(model.QueryFullName) && model.QueryFullName != "")
			{
				sql = sql.Where(x => x.FullName.Contains(model.QueryFullName));
			}
			if (!string.IsNullOrWhiteSpace(model.QueryHasPaid) && model.QueryHasPaid != "")
			{
				var paidSql = model.QueryHasPaid == ConstValues.PaidStatus.已缴费 ? true : false;
				sql = sql.Where(x => x.HasPaid == paidSql);
			}
			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.CreateDate).ThenBy(x => x.FullName).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();
			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				FullName = x.FullName,
				TransferEvidenceId = x.TransferEvidenceId,
				UploadUrl = string.IsNullOrEmpty(x.UploadUrl)? string.Empty : x.UploadUrl.Replace("~","").Replace("\\","/"),
				TotalFee = x.TotalFee,
				Discount = x.Discount,
				Currency = x.Currency,
				HasPaid = x.HasPaid == true ? Resources.HasPaid : Resources.HasNotPaid,
				Sort = x.Sort,
				Status = x.Status,
				Remark = x.Remark,
				CreateDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
						x.CreateDate.Value.ToString("yyyy-MM-dd") :
						x.CreateDate.Value.ToString("MM/dd/yyyy"),
				CreateIP = x.CreateIP,
				Creator = x.Creator
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetEditData(string transferEvidenceId)
		{
			var data = DbContext.ConferenceAttendenceInfo.AsNoTracking().Where(x => x.TransferEvidenceId == transferEvidenceId);
			if (data != null)
			{
				int total = await data.CountAsync();
				var sqlResult = await data.ToListAsync();
				var result = sqlResult.Select(x => new
				{
					ID = x.ID,
					FullName = x.FullName,
					Currency = x.Currency,
					TotalFee = x.TotalFee,
					Discount = x.Discount,
					HasPaid = x.HasPaid == true ? ConstValues.PaidStatus.已缴费 : ConstValues.PaidStatus.未缴费,
				});

				return JsonCamelCase(new
				{
					Total = total,
					Rows = result,
				},
				JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Modify/{ConferenceId}")]
		public async Task<JsonResult> Modify(ConferenceTransferEvidenceModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var allId = model.Ids.Split(ConstValues.chrAnd);
			var conference = await DbContext.ConferenceMaster.FirstOrDefaultAsync(x => x.ID == model.ConferenceId);
			
			for (var index = 0; index < allId.Length; index++)
			{
				string tmp = allId[index];
				var tran = await DbContext.ConferenceAttendenceInfo.FirstOrDefaultAsync(x => x.ID == tmp);
				if (tran != null)
				{
					tran.HasPaid = true;
					tran.ActuallyFee = conference.BenefitStartDate<=model.PayTime && model.PayTime <=conference.BenefitEndDate ? tran.Discount :tran.TotalFee;
					tran.Updater = LoginUser.UserName;
					tran.UpdateDate = DateTime.Now;
					tran.UpdateIP = LoginUser.IP;					
				}
			}
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}
	}
}